package com.linksoul.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

@Slf4j
@Configuration
@MapperScan(
        basePackages = "com.linksoul.mapper",
        sqlSessionFactoryRef = "soulMbtiSqlSessionFactory"
)
public class SoulMbtiDataSourceConfig {

    @Bean(name = "soulMbtiDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.soul-mbti")
    public DataSource soulMbtiDataSource() {
        try {
            return DataSourceBuilder.create().build();
        } catch (Exception e) {
            log.error("【次数据源】连接失败！检查配置: {}", e.getMessage());
            throw new RuntimeException("次数据源初始化失败", e);
        }
    }

    @Bean(name = "soulMbtiTransactionManager")
    public DataSourceTransactionManager soulMbtiTransactionManager(
            @Qualifier("soulMbtiDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "soulMbtiSqlSessionFactory")
    public SqlSessionFactory soulMbtiSqlSessionFactory(
            @Qualifier("soulMbtiDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 可在此处添加MyBatis自定义配置（如分页插件）
        // 关键配置：启用下划线转驼峰
        org.apache.ibatis.session.Configuration configuration =
                new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true); // ✅ 开启驼峰映射
        // 关键修复点：指定模块化XML路径
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath*:/mappers/linkSoul/*.xml")
        );
        return bean.getObject();
    }


}